#pragma once

#include "fmt/core.h"
#include <cstdlib>
#include <string_view>
#include <unistd.h>
#include <vector>
#include <string>
#include <fmt/color.h>

inline std::vector<std::string_view> split(std::string_view str, char delimiter = ' ') {
    std::vector<std::string_view> result;
    size_t start = 0;
    size_t end = str.find(delimiter);

    while (end != std::string_view::npos) {
        result.emplace_back(str.substr(start, end - start));
        start = end + 1;
        end = str.find(delimiter, start);
    }

    // Add the last segment
    result.emplace_back(str.substr(start));

    return result;
}

inline bool programExists(std::string_view program) {

    const auto pathEnv = std::string_view{std::getenv("PATH")};
    if (pathEnv.empty()) {
        return false;
    }

    auto paths = split(pathEnv, ':');
    for(const auto path : paths) {
        std::string fullPath = fmt::format("{}/{}", path, program);
        if (access(fullPath.data(), X_OK) == 0) {
            return true;
        }
    }
    
    return false;
}

inline void printErrorMessage(std::string_view message) {
    fmt::print(fmt::fg(fmt::color::red), "{}\n", message);
}

inline void printInfoMessage(std::string_view message) {
    fmt::print(fmt::fg(fmt::color::green), "{}\n", message);
}

inline void panic(std::string_view message) {
    printErrorMessage(message);
    std::abort();
}